//获取入口文件代码
const fs = require('fs');
const path = require('path');
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default
const babel = require('@babel/core');


const getModuleInfo = (file) => {
    const body = fs.readFileSync(file, 'utf-8');
    const AST = parser.parse(body, {
        sourceType: 'module',
    })

    const deps = {}
    traverse(AST, {
        ImportDeclaration({
            node
        }) {
            const dirname = path.dirname(file)
            const abspath = './' + path.join(dirname, node.source.value)
            deps[node.source.value] = abspath
        }

    });

    const {
        code
    } = babel.transformFromAst(AST, null, {
        presets: ['@babel/preset-env'],
    });

    const moduleInfo = {
        file,
        deps,
        code
    }
    return moduleInfo
}

const parseModules = (file) => {
    const entry = getModuleInfo(file)

    const temp = [entry]
    const depsGraph = {}
    for (let i = 0; i < temp.length; i++) {
        let deps = temp[i].deps
        if (deps) {
            for (let key in deps) {
                if (deps.hasOwnProperty(key)) {
                    const res = getModuleInfo(deps[key])
                    temp.push(res)
                }
            }
        }
    }

    temp.forEach(moduleInfo => {
        depsGraph[moduleInfo.file] = {
            deps: moduleInfo.deps,
            code: moduleInfo.code
        }
    })

    return depsGraph
    // console.log(depsGraph);
}

//将多份代码整理在一起
const bundle = (file) => {
    const depsGraph = JSON.stringify(parseModules(file))
    // console.log(depsGraph);

    return `(function(graph){
        function require(file) {
          function absRequire(relPath) {
            return require(graph[file].deps[relPath])
          }
          var exports = {};
          (function(require, exports, code) {
            eval(code)
          })(absRequire, exports, graph[file].code)
          return exports
        }
        require('${file}')
      })(${depsGraph})`
}

const content =  bundle('./src/index.js')

fs.mkdirSync('./dist')
fs.writeFileSync('./dist/main.js',content)
